// required package imports
import 'dart:async';
import 'package:example/db/dao/login_dao.dart';
import 'package:floor/floor.dart';
import 'package:flutter_scaffold/flutter_scaffold.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'dao/person_dao.dart';
import 'entity/person_table.dart';
import 'entity/login_table.dart';

part 'app_database.g.dart';

const currentVersion = 3;

@Database(version: currentVersion, entities: [Person, Login])
abstract class AppDatabase extends FloorDatabase {
  PersonDao get personDao;

  LoginDao get loginDao;

  // 单例实例
  static AppDatabase? _instance;

  // 获取数据库单例
  static Future<AppDatabase> get instance async {
    if (_instance != null) return _instance!;
    _instance = await _initDatabase();
    return _instance!;
  }

  static Future<AppDatabase> _initDatabase() async {
    return await $FloorAppDatabase
          .databaseBuilder('app_database.db')
          .addMigrations(_migrations())
          .addCallback(
            Callback(
              onCreate: (databse, version) {
                Log.i("===>create database ${version}");
              },
              onUpgrade: (databse, start, end) {
                Log.i("数据库升级:${start}===${end}");
              },
            ),
          )
          .build()
      ..database.setVersion(currentVersion);
  }

  static List<Migration> _migrations() {
    return [
      Migration(1, 2, _migrationV1ToV2),
      Migration(2, 3, _migrationV2ToV3),
    ];
  }

  static Future _migrationV1ToV2(sqflite.Database database) async {
    await database.execute('ALTER TABLE Person ADD COLUMN ege INTEGER');
  }

  static Future _migrationV2ToV3(sqflite.Database database) async {
    await database.execute(
      'CREATE TABLE IF NOT EXISTS Login (id INTEGER KEY, userName TEXT,password TEXT)',
    );
  }
}
